import { ArgumentMetadata, BadRequestException, Injectable, Logger, PipeTransform } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
/**
 * 全局dto参数验证管道
 */
@Injectable()
export class ValidationPipe implements PipeTransform {
  async transform(value: any, metadata: ArgumentMetadata) {
    // return value;
    Logger.log('---------->>>>>>进入全局管道...');
    const object = plainToInstance(metadata.metatype, value);
    if (!metadata.metatype || !this.toValidate(metadata.metatype)) {
      return object;
    }
    // 验证该对象返回出错的数组
    const errors = await validate(object);
    console.log('-----errors--', errors)
    if (errors.length > 0) {
      // 将错误信息数组中的第一个内容返回给异常过滤器
      const errormsg = errors.shift().constraints;
      throw new BadRequestException(errormsg);
    }
    return object;
  }
  // 验证属性值的元类型是否是String, Boolean, Number, Array, Object中的一种
  private toValidate(metatype: any): boolean {
    const types: any[]= [String, Boolean, Number, Array, Object];
    return !types.includes(metatype);
  }
}
